﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.IO;

namespace Common
{
    public class VerifyCodeHelper
    {
        /// <summary>
        /// 生成图形验证码私有类
        /// </summary>
        /// <returns></returns>
        public static byte[] GetVerifyCode(out string chkCode)
        {
            int codeW = 94;
            int codeH = 36;
            int fontSize = 22;//字体大小
            chkCode = string.Empty;
            //颜色
            Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.DarkBlue }; //字体颜色、、
            //字体
            string[] font = { "Times New Roman" };
            char[] character = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
            //生成验证码字符串
            Random rnd = new Random();
            for (int i = 0; i < 4; i++)
            {
                chkCode += character[rnd.Next(character.Length)];
            }

            //创建画布
            Bitmap bmp = new Bitmap(codeW, codeH - 3);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.White);

            //画噪线
            //for (int i = 0; i < 3; i++)
            //{
            //    int x1 = rnd.Next(codeW);
            //    int y1 = rnd.Next(codeH);
            //    int x2 = rnd.Next(codeW);
            //    int y2 = rnd.Next(codeH);

            //    Color clr = color[rnd.Next(color.Length)];
            //    g.DrawLine(new Pen(clr), x1, y1, x2, y2);
            //}
            int nCharWidth = (codeW / 4);
            //画验证码
            for (int i = 0; i < chkCode.Length; i++)
            {
                string fnt = font[rnd.Next(font.Length)];
                Font ft = new Font(fnt, fontSize);
                Color clr = color[rnd.Next(color.Length)];
                g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * nCharWidth, (float)0);
            }
            //将验证码写入图片内存流中，以image/png格式输出
            using (MemoryStream ms = new MemoryStream())
            {
                try
                {
                    //格式
                    bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    return ms.ToArray();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    //释放对象
                    g.Dispose();
                    bmp.Dispose();
                    ms.Dispose();
                }
            }
        }
    }
}
